// diy/components/xcdiytitle.js
var actbilldiyindex = require('../../../model/diy_index')
const cart = require('../../../sys/cart')
var behaviorsbasic = require('../../behavior/basic')

Component({
  behaviors: [behaviorsbasic],
  /**
   * 组件的属性列表
   */
  options: {
    addGlobalClass: true,
    multipleSlots: true
  },
  properties: {
    cid:{  //团长分组id
      type: String,
      default: '',
      observer:function(newval,oldval){
        // console.log("newval")
        // console.log(newval)

      }
    },
    idx:{
      type: Number,
      default: 0
    },
    objmodel: {
      type: Object,
      default: ''
    },
    istop: {
      type: Boolean,
      default: false
    },

    datasource: {
      type: Object,
      default: ''
    },
    heigthcss: {
      type: String,
      default: ''
    },
    cartpro: {
      type: Object,
      default: ''

    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    isseting:false,
    CustomBar: 64,
    actindex: 1,
    actitem: null,
    ischage: false,
    modellist: [],
    isscroll: false,
    istop: false,
    intoid:"",
    scrolltop:0,

  // 自定义滚动
    dotnums: 0,
    
    syswidth: 375,
    scrollWidth: 0,
  },
 
  ready() {
    var updatemodel = {}
    var app = getApp();
    updatemodel["CustomBar"] = app.globalData.CustomBar
    updatemodel["topcss"] = ""
    var objmodel = this.data.objmodel;
    //objmodel.imgdata.imgconfig.rowtype  ==2 

    if (objmodel["tabs"]) {

      if (objmodel["tabs"].isfixed != -1) {
        if (objmodel["tabs"].isfixed == 1) {
          // updatemodel["topcss"] += "position: sticky;"  
          //   updatemodel["topcss"] += "position: fixed;"
        }
        else {
          updatemodel["topcss"] += "position: fixed;max-width:100%;"
        }
        if (objmodel["tabs"]["sticky"]["topset"] == "1") {
          updatemodel["topcss"] += "top: " + (app.globalData.CustomBar - 2) + "px;";
        } else if (objmodel["tabs"]["sticky"]["topset"] == "2") {
          updatemodel["topcss"] += "top: " + app.globalData.Custom.top + "px;";
        } else if (objmodel["tabs"]["sticky"]["topset"] == "3") {
          updatemodel["topcss"] += "top: " + objmodel["tabs"]["sticky"]["customheight"].val / 2 + "px;";
        }
      }
    }

   
 
/// transform(nav, modellist, tabtype)
    updatemodel["modellist"] = this.data.datasource.data;

    if (this.data.objmodel.imgdata.showall == -1 && this.data.datasource.nav) {
      updatemodel["actindex"] = 2
      updatemodel["actitem"] = this.data.datasource.nav[0]
    }

    if(objmodel.imgdata.showall==2){
      updatemodel["actindex"] = 2
      updatemodel["actitem"] = this.data.datasource.nav[0]
     var tranmodelist= this.transformmodelist(this.data.datasource.nav, this.data.datasource.data, objmodel.imgdata.condition.tabtype)
   
     updatemodel["htdata"] =tranmodelist;

    }
    if (!updatemodel["modellist"] || updatemodel["modellist"].length < 1) {
      that = this;
      actbilldiyindex.setstatus(that, "over") // mark: xxx
    }else if(updatemodel["modellist"].length >= this.data.objmodel.imgdata.condition.num){
     
      actbilldiyindex.syspage.loadstatus = "loadmore";
      // actbilldiyindex.setstatus(that, "loadmore") // mark: xxx
    }

    actbilldiyindex.syspage.offset = this.data.datasource.data ? this.data.datasource.data.length : 0
    actbilldiyindex.syspage.limit = this.data.objmodel.imgdata.condition.num
    this.setData(updatemodel)
 

    var that =this;
    if(objmodel.imgdata.showall==2)
    {
      this._observer = wx.createIntersectionObserver(this,{observeAll:true,  thresholds: [0]})
    
      this._observer
        .relativeTo('.xttd')
        .observe('.smtit', (res) => {
          if(that.data.isseting)
          {
          
            return 
          }
         var idx= res.dataset.idx
    
         if(res.boundingClientRect.top<100)
         {
          if(res.intersectionRatio>0){
            idx= idx - 1
          } 
          if(idx<0){
            idx=0
          }           
         
          that.setData({actindex:idx+2 })
         }  
         
        })
    } 
    else
    {
      that.createIntersectionObserver({
        thresholds: [0.8, 0.95, 100]
        //  thresholds: [0.6,0.9]
      }).relativeToViewport().observe('.scrollcont', (res) => {
        if (res.intersectionRect.top <= 60) {
          if (that.data.isscroll == false) {
            this.setData({ isscroll: true })
          }
        }
        else {
          if (that.data.isscroll == true) {
            this.setData({ isscroll: false })
          }
        }
      })
    }

    if(this.data.objmodel.imgdata.imgconfig.rowtype==2){
      this.setData({
        scrolltop: 1,
        syswidth: wx.getSystemInfoSync().windowWidth
      })
    }


   
  },
  /**
   * 组件的方法列表
   */
  methods: {
    initsiper(ev) {     
     
      var scrollWidth = ev.detail.scrollWidth
      var syswidth = this.data.syswidth
      var mod_val = scrollWidth % syswidth
      var dotnums = (scrollWidth - mod_val) / syswidth + (mod_val > 0 ? 1 : 0)    

     
      this.setData({ scrolltop: 0, scrollWidth, dotnums })
    },
    changescrollleft(ev) {
      switch (ev.op) {
        case "setleft": {
          var scrollleft = this.data.syswidth * ev.idx
          if (this.data.scrolltop == scrollleft) {
            scrollleft--
          }
          this.setData({ scrolltop: scrollleft })
          break;
        }
      }
    },
    transformmodelist(nav, modellist, tabtype) {
      var htdata = [];
      nav.forEach(item => {
        htdata[item.id] =[]
      })
      modellist.forEach(item => {
        if (tabtype == 'proclass') {
          if (htdata[item.spid]) {
            htdata[item.spid].push(item)
          } else if (htdata[item.bpid]) {
            htdata[item.bpid].push(item)
          }
        }
        else if (tabtype == 'label') {
          if (item.tagsids) {
            item.tagsids = item.tagsids.split(",")
            item.tagsids.forEach(itemx => {
              if (htdata[itemx]) {
                htdata[itemx].push(item)
              }


            })
          }
        }
      })

      return htdata;

    },
    //objmodel.imgdata['showall']
    noevent(ev) {
      //用来阻止用的， 其它没什么用处

 
    },
    onChangexx(e) {
      var detail = {};
      detail["idx"] = e.detail.name;

      if (detail["idx"] == 1) {
        detail["item"] = null
      }
      else {
        // var index= detail["idx"] - (this.data.objmodel.imgdata['showall']==1 ? 1:2)
        detail["item"] = this.data.datasource.nav[detail["idx"] - 2]
      }
    

      this.tabchange({ detail })

    },
    tabchange(e) {
  

      var that = this;
      var updatemodel = {};
      updatemodel["actindex"] = e.detail.idx
      updatemodel["actitem"] = e.detail.item
      var objmodel = this.data.objmodel
      updatemodel["scrolltop"] =this.data.scrolltop?0:-1
     
  
     
     


     
      if(objmodel.imgdata.showall==2){
        updatemodel["intoid"]="smtit_" +(e.detail.idx - 2 ) 
      
        
        this.data.isseting=true
        setTimeout(() => {
          that.data.isseting=false
        }, 100);
      }
      this.setData(updatemodel)
      if(objmodel.imgdata.showall!=2)
      {
        that.getpagelist(that, 1).then(function(){


          if(objmodel.imgdata.imgconfig.rowtype==2 && objmodel.imgdata.imgconfig['indicator']){
            var nupdate={}

            nupdate["dotnums"] =0
            nupdate["scrolltop"] =that.data.scrolltop==1?2:1
            setTimeout(function(){
              that.setData(nupdate);
            },100)
          
          }


        })
        if (this.data.objmodel.tabs && this.data.objmodel.tabs.isfixed != -1) {
          this.triggerEvent("pagescrollto", {})
        }
      }   
    },

    getcondition() {

      var app = getApp();
      var proconfig = app.globalData.configdata.proconfig
      var condition = JSON.parse(JSON.stringify(this.data.objmodel.imgdata.condition))

      var actindex = this.data.actindex
      var actitem = this.data.actitem
      switch (condition.tabtype) {
        case "proclass": {
          if (actindex != 1) {
            delete condition["mxpid"]
            if (actitem["pid"] == 0 && proconfig.proclass.level == 2) {
              condition["bpid"] = actitem["id"]
            }
            else {
              condition["bpid"] = actitem["id"]
            }
          }
          break;
        }
        case "label": {
          if (actindex != 1) {
            condition["tags"] = actitem["id"]
          }
          break
        }
      }
      return condition
    },
    scrolltolowe(e) {
      var para = this.getcondition()
      var that = this;
   
      this.getpagelist(that, -1, para)
    },


    pagebottom() {
      
      if (this.data.objmodel.loadmode == "1") {
        console.log("this.data.objmodel")

        console.log(this.data.objmodel)
        this.scrolltolowe();
      }
    },

    getpagelist(that, rest, strwhere) {
 
      return new Promise(function(resolve){
        if (rest == 1) {

          strwhere = that.getcondition()
           
        }
        // if(strwhere['num']){
        //   strwhere['limit']=strwhere['num']
        // }
  
        actbilldiyindex.tabprooffset(that, rest, strwhere).then(function (result) {
          var updatemdoel = {};
          console.log("result")
          console.log(result)
          if ((result["code"] == "over" && result["obj"]) || result["code"] == "loadmore") {
            for (var a in result["obj"]["modellist"]) {
              if (result["obj"]["modellist"][a]['snapshot']) {
                result["obj"]["modellist"][a]["snapshot"] = JSON.parse(result["obj"]["modellist"][a]["snapshot"])
              }
            }
            if (rest == 1) {
              updatemdoel["modellist"] = result["obj"]["modellist"];
            }
            else {
              if (result["obj"]["modellist"].length > 0) {
                updatemdoel["modellist"] = that.data.modellist.concat(result["obj"]["modellist"]);
              }
            }
          }
          wx.stopPullDownRefresh();
          
          that.setData(updatemdoel);

          resolve({status:1})
        });
      })
    
    },
    cartop(ev) {
 
      var detail = ev.detail;
      var item = detail.item;
      switch (detail.op) {
        case "setnum": {
          var keyval = item.id + "_0_0_-1_1";
          cart.setnum(keyval, detail.num, true);
          break;
        }
        case "add": {         
          if (item.guigetype == "-1") {
            item["num"] = 1
            cart.cartadd(item)
          }
          else {
            this.triggerEvent('buy', { dataset: detail })
          }
          break;

        }

      }
      this.triggerEvent('cartop', { op: "reload" })
    },
    buy(ev) {
      var dataset = ev.currentTarget;
      this.triggerEvent('buy', dataset)
    },
    bindscrollc(ev) {
      if (this.data.objmodel.loadmode == 1||this.data.objmodel.loadmode == 3) {
        return
      }

      if (ev.detail.deltaY < 0) {
        if (!this.data.istop) {
          this.data.istop = true
          var selector=".diytabprocom .idx_tabpro_"+this.data.idx
          wx.pageScrollTo({
            selector: selector,
            duration: 300,
          }
          )
        }

      }
      else {
        if (this.data.istop == true) {
          this.data.istop = false
        }

      }
    }
  }
})
